﻿using AutoUpdater.Bll;
using AutoUpdater.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace AutoUpdater
{
    public class CsUpdateSelf
    {
        private string updateExeName;
        public event Action<bool,string> UpdateCompleted;

        private Thread thread;

        public CsUpdateSelf()
        {
        }

        public void Start()
        {
            if(thread != null)
            {
                try
                {
                    thread.Abort();
                }
                catch (Exception ex) { }
            }

            thread = new Thread(DealUpdate);
            thread.Start();
        }

        private void DealUpdate()
        {
            //如果启动的是exe2，复制文件到exe
            //  继续往下执行；
            //1. 获取本地程序版本号
            //2. 获取服务端自动更新程序版本号
            //3. 如果需要更新 
            //      复制一个updateexe2
            //        结束运行重新启动
            //4. 
            //

            string pathName = System.Windows.Forms.Application.ExecutablePath;
            string directoryPath = System.Windows.Forms.Application.StartupPath;

            //如果启动的是exe2，复制文件到exe
            if (!updateExeName.Equals(pathName))
            {
                FileInfo fileInfo = new FileInfo(pathName);
                fileInfo.CopyTo(Path.Combine(directoryPath, updateExeName));
                VersionXmlUtil.SetUpdateExeVersion(VersionXmlUtil.GetUpdateExeCurrentUpdateVersion());
                UpdateCompleted(true,null);
                return;
            }

            //1. 获取本地程序版本号
            string version = VersionXmlUtil.GetUpdateExeVersion();

            FileCheckReq fileCheckReq = new FileCheckReq();
            fileCheckReq.clientVersion = version;
            var contract = FileCheckBll.CheckUpdateExeFile(fileCheckReq);

            if(contract != null)
            {
                VersionXmlUtil.SetUpdateExeCurrentUpdateVersion(contract.clientVersion);

                if (contract.updateFiles != null && contract.updateFiles.Count > 0)
                {
                    foreach (var file in contract.updateFiles)
                    {
                        int start = 0;
                        while (start < file.fileSize)
                        {
                            byte[] fileByte = FileCheckBll.DownLoadFile(file, 0);
                            //Path.Combine(directoryPath, file.filePath, file.fileName)
                            // 写入文件
                        }
                    }

                    UpdateCompleted(true, "upateexe2.exe");
                    return;
                }
            }
            UpdateCompleted(true, null);
        }
    }
}
